<template>
  <LayoutNav></LayoutNav>
  <div class="container">
  <div class="factory-detail">
    <!-- 工厂基本信息卡片 -->
    <el-card class="info-card">
      <div class="factory-info">
        <div class="left">
          <el-avatar :size="100" :src="factoryInfo.logo" />
          <div class="certification">
            <el-tag type="success" v-if="factoryInfo.status==='1'">已认证工厂</el-tag>
          </div>
        </div>
        
        <div class="right">
          <h2 class="name">{{ factoryInfo.factoryName }}</h2>
          <div class="basic-info">
            <div class="info-item">
              <el-icon><Location /></el-icon>
              <span>地址：{{ factoryInfo.location }}</span>
            </div>
            <div class="info-item">
              <el-icon><Phone /></el-icon>
              <span>联系电话：{{ factoryInfo.phone }}</span>
            </div>
            <div class="info-item">
              <el-icon><Suitcase /></el-icon>
              <span>描述：{{ factoryInfo.description }}</span>
            </div>
            <div class="info-item">
              <el-icon><Box /></el-icon>
              <span>起订量：{{ factoryInfo.minOrder }}件</span>
            </div>
          </div>
          
          <div class="actions">
            <el-button type="primary" @click="handleContact">联系工厂</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 工厂详细信息 -->
    <el-tabs class="factory-tabs">
      <!-- 众筹定制 -->
      <el-tab-pane label="众筹定制">
    <div class="crowdfunding-list">
      <!-- 筛选栏 -->
      <div class="filter-bar">
        <el-radio-group v-model="fundingStatus" size="large">
          <el-radio-button label="all" value="all">全部</el-radio-button>
          <el-radio-button label="funding" value="funding">众筹中</el-radio-button>
          <el-radio-button label="success" value="success">已达成</el-radio-button>
          <el-radio-button label="failed" value="failed">未达成</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 众筹列表 -->
      <el-row :gutter="20">
        <el-col 
          :xs="24" 
          :sm="12" 
          :md="8" 
          v-for="item in filteredCrowdfundingList" 
          :key="item.id"
        >
          <el-card class="funding-card" shadow="hover">
            <el-image :src="item.image" fit="cover" class="product-image" />
            <div class="funding-info">
              <h4 class="title">{{ item.title }}</h4>
              <p class="desc">{{ item.description }}</p>
              
              <!-- 众筹进度 -->
              <div class="progress-info">
                <el-progress 
                  :percentage="((item.currentQuantity / item.targetQuantity) * 100).toFixed(1) "
                  :status="getProgressStatus(item)"
                />
                <div class="numbers">
                  <span class="current">已筹：{{ item.currentQuantity }}件</span>
                  <span class="target">目标：{{ item.targetQuantity }}件</span>
                </div>
              </div>
              
              <!-- 价格和剩余时间 -->
              <div class="price-time">
                <span class="price">¥{{ item.price }}/件</span>
                <span class="time" :class="{ urgent: isUrgent(item.endTime) }">
                  剩余 {{ getRemainTime(item.endTime) }}
                </span>
              </div>
              
              <!-- 操作按钮 -->
              <div class="actions">
                <el-button 
                  type="primary" 
                  :disabled="!canJoin(item)"
                  @click="handleJoinFunding(item)"
                >
                  {{ getFundingButtonText(item) }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </el-tab-pane>

  <el-tab-pane label="全部商品">
      <div class="goods-section"> 
        <div class="section-header">
          <h3>全部商品</h3>
          <div class="filters">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索商品"
              prefix-icon="Search"
              clearable
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" @click="handleSearch">搜索商品</el-button>
          </div>
        </div>

        <!-- 商品列表 -->
        <el-row :gutter="20">
          <el-col 
            :lg="6" 
            v-for="item in pageList" 
            :key="item.good_id"
          >
            <el-card 
              class="goods-card" 
              shadow="hover"
              @click="goToGoodsDetail(item.good_id)"
            >
              <el-image 
                :src="item.images" 
                fit="cover"
                class="goods-image"
              />
              <div class="goods-info">
                <h4 class="goods-name">{{ item.good_name }}</h4>
                <p class="goods-desc">{{ item.description }}</p>
                <div class="goods-price">
                  <span class="price">¥{{ item.price }}</span>
                  <span class="min-order">起订量：{{ item.minOrder }}件</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
  </el-tab-pane>
</el-tabs>
  </div>
  </div>
  <LayoutFooter/>
</template>

<script setup>
import { ref, onMounted,computed,watch} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Location, Phone, Suitcase, Box } from '@element-plus/icons-vue'
import LayoutNav from '../Layout/components/LayoutNav.vue';
import LayoutFooter from '../Layout/components/LayoutFooter.vue';
import { getGoodsListAPI } from '@/api/store'
import { getFactoryInfoAPI ,getCrowdfundingListAPI } from '@/api/factory'

const route = useRoute()
const router = useRouter()

const factoryInfo = ref({})
const factoryId = ref(null)

// 获取加工厂信息
const getfactoryInfo = async () => {
  const res = await getFactoryInfoAPI(route.params.userId)
  factoryId.value = res.data.factoryId
  getcrowdfundingList()
  factoryInfo.value = res.data
}

const goodsList = ref([])
const pageList = ref([]); // 当前页的数据（用于显示）
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 获取商品列表
const getGoodsList = async () => {
  const res = await getGoodsListAPI(route.params.userId)
  // console.log(res.data)
  goodsList.value = res.data
  total.value = goodsList.value.length
  updatePaginatedList();   // 更新分页数据
}
getGoodsList()

const searchKeyword = ref('')

// 添加一个计算属性用于过滤商品列表
const filteredGoodsList = computed(() => {
  if (!searchKeyword.value) {
    return goodsList.value
  }
  return goodsList.value.filter(item => 
    item.good_name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 添加搜索处理方法
const handleSearch = () => {
  currentPage.value = 1 // 重置页码到第一页
  updatePaginatedList()
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  if(searchKeyword.value === '')
  handleSearch()
})

// 联系工厂
const handleContact = () => {
  router.push({
    path: '/customer',
    query: {
      targetId: route.params.id,
      targetName: factoryInfo.value.name,
      targetType: 'factory'
    }
  })
}

const fundingStatus = ref('all')
const crowdfundingList = ref([
  {
    id: 1,
    title: '2024春季新款连衣裙定制',
    description: '法式复古风格，采用优质面料，精细工艺',
    image: 'https://img.diytrade.com/smimg/122287/49109632-11320001-0/%E8%A1%AC%E8%A1%AB/284c.png',
    currentAmount: 80,
    targetAmount: 100,
    price: 199,
    endTime: '2024-03-01 23:59:59',
    status: 'funding' // funding, success, failed
  },
    {
    id: 1,
    title: '2024春季新款连衣裙定制',
    description: '法式复古风格，采用优质面料，精细工艺',
    image: 'https://img.diytrade.com/smimg/122287/49109630-11319999-0/%E8%A1%AC%E8%A1%AB/2977.png',
    currentAmount: 80,
    targetAmount: 100,
    price: 199,
    endTime: '2024-12-01 23:59:59',
    status: 'funding' // funding, success, failed
  },
])

const getcrowdfundingList = async () => {
  const res = await getCrowdfundingListAPI(factoryId.value)
  crowdfundingList.value = res.data
}


// 添加筛选计算属性
const filteredCrowdfundingList = computed(() => {
  if (fundingStatus.value === 'all') {
    return crowdfundingList.value
  }
  
  return crowdfundingList.value.filter(item => {
    // 众筹中：状态为funding且未过期
    if (fundingStatus.value === 'funding') {
      return item.status === 'funding' && new Date(item.endTime) > new Date()
    }
    // 已达成：当前数量达到目标数量
    if (fundingStatus.value === 'success') {
      return item.currentAmount >= item.targetAmount
    }
    // 未达成：已过期但未达到目标数量
    if (fundingStatus.value === 'failed') {
      return new Date(item.endTime) <= new Date() && 
      item.currentAmount < item.targetAmount
    }
    return false
  })
})

// 判断众筹状态的方法
const getProgressStatus = (item) => {
  if (item.currentAmount >= item.targetAmount) return 'success'
  if (item.status === 'failed') return 'exception'
  return ''
}

// 计算剩余时间
const getRemainTime = (endTime) => {
  const end = new Date(endTime)
  const now = new Date()
  const diff = end - now

  if (diff <= 0) return '已结束'
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  
  return days > 0 ? `${days}天` : `${hours}小时`
}

// 判断是否紧急（24小时内）
const isUrgent = (endTime) => {
  const end = new Date(endTime)
  const now = new Date()
  return (end - now) <= 24 * 60 * 60 * 1000
}

// 判断是否可以参与众筹
const canJoin = (item) => {
  const endTime = new Date(item.endTime.replace(' ', 'T'));
  const currentDate = new Date();
return item.status === 'funding' &&
        item.currentQuantity < item.targetQuantity &&
        endTime > currentDate;
}

// 获取按钮文字
const getFundingButtonText = (item) => {
  if (item.status === 'success') return '已达成'
  if (item.status === 'failed') return '未达成'
  if (new Date(item.endTime) <= new Date()) return '已结束'
  return '立即参与'
}

// 处理参与众筹
const handleJoinFunding = (item) => {
    const routeData = router.resolve({
    name: 'crowdFundingDetail',
    params: { projectid: item.projectId }
  })
  // 在新窗口打开
  window.open(routeData.href, '_blank')
}

// 分页处理
// 修改更新分页数据的方法，使用过滤后的列表
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  // 使用过滤后的列表
  pageList.value = filteredGoodsList.value.slice(start, end)
  // 更新总数
  total.value = filteredGoodsList.value.length
}

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

//跳转商品详情
const goToGoodsDetail = (id) => {
  const routeData = router.resolve({
    name: 'goodDetail',
    params: { userId: factoryInfo.value.userId, goodId: id }
  })
  // 在新窗口打开
  window.open(routeData.href, '_blank')
}

onMounted(() => {
  getfactoryInfo()
  getGoodsList()
})
</script>

<style lang="scss" scoped>
.container{
  min-height: 100vh;
}
.factory-detail {
  padding: 20px;
  min-height: 100vh;
  .info-card {
    margin-bottom: 20px;

    .factory-info {
      display: flex;
      gap: 20px;

      .left {
        text-align: center;
        
        .certification {
          margin-top: 10px;
        }
      }

      .right {
        flex: 1;

        .name {
          margin: 0 0 15px 0;
          font-size: 24px;
        }

        .basic-info {
          .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            color: #666;

            .el-icon {
              margin-right: 8px;
            }
          }
        }

        .actions {
          margin-top: 20px;
        }
      }
    }
  }
  .crowdfunding-list {
    min-height: 100vh;
  .filter-bar {
    margin-bottom: 20px;
    text-align: center;
  }

  .funding-card {
    margin-bottom: 20px;
    
    .product-image {
      width: 100%;
      height: 200px;
      object-fit: cover;
    }
    
    .funding-info {
      padding: 15px;
      
      .title {
        margin: 0 0 8px;
        font-size: 16px;
        font-weight: bold;
      }
      
      .desc {
        color: #666;
        font-size: 14px;
        margin-bottom: 15px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-box-orient: vertical;
      }
      
      .progress-info {
        margin-bottom: 15px;
        
        .numbers {
          display: flex;
          justify-content: space-between;
          font-size: 13px;
          color: #666;
          margin-top: 5px;
        }
      }
      
      .price-time {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        .price {
          color: #ff6b6b;
          font-size: 18px;
          font-weight: bold;
        }
        
        .time {
          color: #666;
          font-size: 14px;
          
          &.urgent {
            color: #ff6b6b;
          }
        }
      }
      
      .actions {
        text-align: center;
      }
    }
  }
}
}

 .goods-section {
    min-height: 100vh;
    position: relative;
    .pagination{
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      bottom: 20px;
    }
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
      }
      
      .filters {
        display: flex;
        gap: 15px;
      }
    }
    
    .goods-card {
      margin-bottom: 20px;
      cursor: pointer;
      
      .goods-image {
        width: 100%;
        height: 200px;
      }
      
      .goods-info {
        padding: 10px;
        
        .goods-name {
          margin: 0 0 8px 0;
          font-size: 16px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .goods-desc {
          color: #666;
          font-size: 14px;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price {
            color: #ff6b6b;
            font-size: 18px;
            font-weight: bold;
          }
          
          .min-order {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

</style>